package com.server.questionbank.snframe.controller.Login;

import com.server.questionbank.snframe.domain.User.TUser;
import com.server.questionbank.snframe.service.UsersService.UsersService;
import com.server.questionbank.snframe.util.MinIo.MinIoBucket;
import com.server.questionbank.snframe.util.MinIo.MinIoFactory;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;

@RestController
@RequestMapping("/users/overt")
public class UsersOvertController {
    @Autowired
    UsersService usersService;
    @Autowired
    MinIoFactory minIoFactory;

    // 获取头像
    @GetMapping("/avatar")
    @ApiOperation("用户头像")
    public void previewAvatar(@RequestParam("userId") Long userId, HttpServletResponse response) throws Exception {
        TUser user = usersService.selectUserById(userId);
        if (user == null) {
            response.setStatus(404);
            return;
        }
        String userAvatarPath = user.getUserId() + "/avatar/" + user.getAvatar();
        if (userAvatarPath == null || userAvatarPath.isEmpty()) {
            response.setStatus(404);
            return;
        }
        MinIoBucket minIoBucket = minIoFactory.openBucket("user");
        try (InputStream inputStream = minIoBucket.downloadFile(userAvatarPath)) {
            String contentType = minIoBucket.getFileType(userAvatarPath);
            response.setContentType(contentType);
            IOUtils.copy(inputStream, response.getOutputStream());
        } catch (Exception e) {
            response.setStatus(404);
        }
    }
}
